package com.dz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dz.reggie.common.R;
import com.dz.reggie.dto.DishDto;
import com.dz.reggie.entity.Category;
import com.dz.reggie.entity.Dish;
import com.dz.reggie.entity.DishFlavor;
import com.dz.reggie.service.CategoryService;
import com.dz.reggie.service.DishFlavorService;
import com.dz.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @param page
     * @param pageSize
     * @param name
     * @return 使用DishDto: categoryId显示菜品分类名称categoryName
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {

        // 1、构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        // 2 构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 3 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByAsc(Dish::getUpdateTime);
        // 4 查询数据
        dishService.page(pageInfo, queryWrapper);

        // 处理: categoryId显示菜品分类名称categoryName
        // 对象拷贝: records需要作处理, 其他分页数据拷贝进去
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        // 通过Stream流将属性拷贝, 并单独给categoryName修改值
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            // 将其他属性拷贝
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 查询菜品分类对应的菜品数据（列表）
     * 注意，前端是带参数传递请求方法（?id&），并不是路径参数请求(/id)，所以无需PathVariable
     */
    // @GetMapping("/list")
    // public R<List<Dish>> queryDishes(Dish dish){
    //
    //     // 构造查询条件
    //     LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    //     queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
    //     // 只显示在售的菜品
    //     queryWrapper.eq(Dish::getStatus, 1);
    //     queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
    //     List<Dish> dishes = dishService.list(queryWrapper);
    //     return R.success(dishes);
    // }

    /**
     * 客户端展示菜品列表
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> queryDishes(Dish dish) {
        // 构建key，便于Redis缓存存取
        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        log.info("key:{}", key);

        // 从redis缓存中获取数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null)
            return R.success(dishDtoList);

        // 缓存中无数据则从表中获取：
        // 构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 只显示在售的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishService.list(queryWrapper);

        // 设置上每道菜的口味信息
        dishDtoList = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            // 将其他属性拷贝
            BeanUtils.copyProperties(item, dishDto);

            // 根据菜品id条件，查询菜品口味集合
            LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper<>();
            flavorQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(flavorQueryWrapper);
            if (flavorList != null) {
                dishDto.setFlavors(flavorList);
            }
            return dishDto;
        }).collect(Collectors.toList());
        // 将查询到的数据放入Redis缓存中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);

    }


    /**
     * 无法使用@ResponsBody Dish dish，因为前端传输的数据与实体类属性并不对应
     * 因此使用DishDto，扩展接收页面提交的数据类型
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        // 需要操作两张表
        dishService.saveWithFlavor(dishDto);

        // 清理所有菜品的缓存数据
        // Set keys = redisTemplate.keys("dish_*");
        // redisTemplate.delete(keys);
        // 精确清理某个分类下的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("添加菜品成功");
    }

    /**
     * 菜品删除，批量删除
     * 应该先删除与菜品绑定的菜品口味表中的菜品口味数据，
     * 再删除菜品表中的菜品数据（与新增操作顺序反序）
     *
     * @param idList 菜品id
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") ArrayList<Long> idList) {
        log.info("ids={}", idList);

        // 遍历List，精确清理分类下的菜品缓存数据
        for (Long id : idList) {
            Long categoryId = dishService.getById(id).getCategoryId();
            String key = "dish_" + categoryId + "_1";
            redisTemplate.delete(key);
        }
        dishService.deleteByIdsWithFlacor(idList);
        return R.success("删除成功！");
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        // 清理所有菜品的缓存数据
        // Set keys = redisTemplate.keys("dish_*");
        // redisTemplate.delete(keys);
        // 精确清理某个分类下的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功！");
    }

    /**
     * 启售
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> startDishStatus(@RequestParam ArrayList<Long> ids) {
        log.info("ids={}", ids);

        dishService.openDishStatus(ids);
        return R.success("状态修改成功");
    }

    /**
     * 停售
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> closeDishStatus(@RequestParam ArrayList<Long> ids) {
        log.info("ids={}", ids);

        dishService.closeDishStatus(ids);
        return R.success("状态修改成功");
    }
}